﻿using System;
using GpgCore.Corporations;
using GpgCore.GameWorld;
using GpgCore.Products;

namespace GpgCore.CityItems
{
    public class Shop : CityItem
    {
        public ProductType TradingProduct;
        public CityOffice OwnOffice;
        public int Level = 1;
        public ShopScheme Scheme;
        public int NeedWorkers
        {
            get { return Level * Scheme.WorkersPerLevel; }
        }
        public int ActualWorkers;
        public double Productivity;
        public double PaymentPerWorker;
        public double MinSalePrice;
        public double MaxSaleCount;

        public Shop(City ownCity, ProductType tradingProduct, CityOffice ownOffice)
            : base(ownCity)
        {
            TradingProduct = tradingProduct;
            OwnOffice = ownOffice;
            Scheme = ShopScheme.Schemes[tradingProduct];
            OwnCity.CityItems.Add(this);
            OwnOffice.Shops.Insert(tradingProduct, this);
        }

        public override void Morning()
        {
            var payment = PaymentPerWorker * NeedWorkers;
            payment = OwnOffice.ExtractMoney(payment);
            OwnCity.Exchanges[ProductType.Employees].OpenPositionWithMoney(payment, this);
            base.Morning();
        }

        private void DoSales()
        {
            if (OwnCity.Exchanges[TradingProduct].CurrentSalePrice > MinSalePrice)
                OwnOffice.Money += OwnCity.Exchanges[TradingProduct].GetMyMoney(this);
            var prodCount = MaxSaleCount >= 0 ? Math.Min(MaxSaleCount, Scheme.MaxDailySales * Level) : Scheme.MaxDailySales * Level;
            prodCount *= Productivity;
            if (prodCount > 0)
            {
                prodCount = OwnOffice.Warehouse.ExtractProduct(prodCount, TradingProduct);
                OwnCity.Exchanges[TradingProduct].OpenPositionWithProduct(prodCount, this);
            }
        }

        public override void Evening()
        {
            ActualWorkers = (int)OwnCity.Exchanges[ProductType.Employees].GetMyProduct(this);
            Productivity = (double)ActualWorkers / NeedWorkers;
            Productivity = Math.Min(Productivity, 2);
            DoSales();
            base.Evening();
        }
    }
}
